package cn.t12.qg.payconsumer.controler;

import cn.t12.qg.payconsumer.config.QGWxPayConfig;
import cn.t12.qg.payconsumer.service.LocalPayService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.qg.dto.ReturnResult;
import com.qg.dto.ReturnResultUtils;
import com.qg.pojo.QgOrder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class PayController {

    @Resource
    private LocalPayService localPayService;

    @GetMapping("/prepay/{orderNo}")
    public ReturnResult prepay(@PathVariable String orderNo){
        QgOrder qgOrder = localPayService.getByOrderNo(orderNo); ;
        return ReturnResultUtils.returnSuccess(qgOrder);
    }

    @Resource
    private QGWxPayConfig wxPayConfig;
    @GetMapping("/wxpay/createqccode/{orderNo}")
    public ReturnResult createqccode(@PathVariable String orderNo) throws Exception {
        QgOrder qgOrder = localPayService.getByOrderNo(orderNo);
        WXPay wxpay = new WXPay(wxPayConfig);
        Map<String, String> data = new HashMap<String, String>();
        // 根据商品id获取商品名
        data.put("body", "商品xxxx");
        data.put("out_trade_no",qgOrder.getOrderNo());
        data.put("device_info", "");
        data.put("fee_type", "CNY");
       // data.put("total_fee", qgOrder.getAmount()*100+"");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "127.0.0.1");
        data.put("notify_url", wxPayConfig.getNotifyUrl());
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        data.put("product_id", "12");
        Map<String, String> resp = null;
        try {
            resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,String> responseData = new HashMap<>();
        responseData.put("codeUrl",resp.get("code_url"));
        return ReturnResultUtils.returnSuccess(responseData);
    }

    // 微信支付的回调
    @PostMapping("/wxpay/cb")
    public void wxPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 从请求中获取发送过来的xml数据
        ServletInputStream inputStream = request.getInputStream();
        InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader reader = new BufferedReader(inputReader);
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        System.out.println("回调接收到的数据:");
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            stringBuilder.append(line);
        }
        reader.close();
        inputReader.close();
        inputStream.close();
        // 把接收到的xml转换为map
        Map<String, String> requestMap = WXPayUtil.xmlToMap(stringBuilder.toString());

        WXPay wxpay = new WXPay(wxPayConfig);
        System.out.println("map结果:");
        System.out.println(requestMap);
        // 验证内容是否正确的
        Map<String, String> responseMap = new HashMap<>();
        //  if (wxpay.isPayResultNotifySignatureValid(requestMap)) {
        if (WXPayUtil.isSignatureValid(requestMap, wxPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256)) {
            System.out.println("签名正确");
            // 签名正确
            // 进行处理。
            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            //TODO 支付成功的情况下,要把对应订单的支付状态更新为已支付  幂等操作
            // 返回结果
            responseMap.put("return_code", "SUCCESS");
            responseMap.put("return_msg", "OK");
        } else {
            // 签名错误，如果数据里没有sign字段，也认为是签名错误
            System.out.println("签名错误");
            responseMap.put("return_code", "FAIL");
            responseMap.put("return_msg", "签名失败");
        }
        // 把map转为xml
        String responseXml = WXPayUtil.mapToXml(responseMap);
        response.getWriter().write(responseXml);
    }

}
